package com.noname.lib_base_java.net.download;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.reflect.TypeToken;
import com.noname.lib_base_java.util.L;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.List;

import okhttp3.ResponseBody;

/**
 * Author: Lmoumou
 * Date: 2019-01-22 11:46
 * 文件名: FileUtil
 * 描述:
 */
public class FileUtil {
    /**
     * 写入文件
     *
     * @param file
     * @param info
     * @throws IOException
     */
    public static void writeCache(ResponseBody body, File file, DownloadInfo info) throws Exception {
        if (file.exists() && body.contentLength() == file.length()) {
            file.delete();
        }
        File sFutureStudioIconFile = new File(info.getSavePath());
        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            byte[] fileReader = new byte[4096];
            inputStream = body.byteStream();
            outputStream = new FileOutputStream(sFutureStudioIconFile, true);
            while (true) {
                int read = inputStream.read(fileReader);
                if (read == -1) {
                    break;
                }
                outputStream.write(fileReader, 0, read);
            }
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void writeDownloadInfo(DownloadInfo info) throws JSONException {
        L.e("FileUtil", "length->"+info.getContentLength());
        if (info.getContentLength() != 0) {
            File file = new File(info.getInfoSavePath());
            try {
                if (file.exists()) {
                    String content = readTxtFile(file);
                    List<DownloadInfo> contentList = new Gson().fromJson(content, new TypeToken<List<DownloadInfo>>() {
                    }.getType());
                    for (DownloadInfo downloadInfo : contentList) {
                        if (info.getThesaurus_id().equals(downloadInfo.getThesaurus_id())) {
                            contentList.remove(downloadInfo);
                        }
                    }
                    contentList.add(info);

                    JsonArray jsonArray=new Gson().toJsonTree(contentList,new TypeToken<List<DownloadInfo>>(){}.getType()).getAsJsonArray();

                    file.delete();
                    file.createNewFile();
                    writeContent(jsonArray.toString(), file);
                } else {
                    JSONArray jsonArray = new JSONArray();
                    Gson gson = new Gson();
                    String s = gson.toJson(info);
                    jsonArray.put(new JSONObject(s));

                    file.createNewFile();
                    writeContent(jsonArray.toString(), file);
                }
            } catch (IOException e) {
                e.printStackTrace();
                L.e("writeDownloadInfo", "异常->" + e.getMessage());
            }
        }

    }

    /**
     * 写入内容
     *
     * @param s
     * @param file
     * @throws IOException
     */
    private static void writeContent(String s, File file) throws IOException {
        RandomAccessFile raf = new RandomAccessFile(file, "rwd");
        raf.seek(file.length());
        raf.write(s.getBytes());
        raf.close();
    }

    /**
     * 读TXT文件内容
     *
     * @param fileName
     * @return
     */
    public static String readTxtFile(File fileName) throws IOException {
        String result = "";
        FileReader fileReader = null;
        BufferedReader bufferedReader = null;
        try {
            fileReader = new FileReader(fileName);
            bufferedReader = new BufferedReader(fileReader);
            try {
                String read = null;
                while ((read = bufferedReader.readLine()) != null) {
                    result = result + read + "\r\n";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
            if (fileReader != null) {
                fileReader.close();
            }
        }
        L.e("readTxtFile", result);
        return result;
    }

}
